using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Framework.Library.Components.Security;
using Framework.Library.Components.Commands;
using Framework.Library;
using Framework.Library.Utilities.Database;
using Framework.Library.Components.Database;
using Framework.Library.Utilities;

namespace Framework.Portal.Administrator.Database
{
    public partial class StoreProperty : AuthenticatedControl
    {
        _StoredProcedure objProc = new _StoredProcedure();
        private DataTable privilegesDataTable;

        protected void dropProcedure_SelectedIndexChanged(object sender, EventArgs e)
        {
            objProc.ID = Convert.ToInt64(dropProcedure.SelectedValue);
            objProc.LoadProperties();
            loadProperties(objProc);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if ((!CurrentUser.IsSuperAdmin && CommandController.IsSystemModule(AppEnv.CommandID())) || !CommandController.IsAvailableForUser(AppEnv.CommandID(), CurrentUser.UserID, Convert.ToInt32(AppEnv.PortalId())))
                Response.Redirect(AppEnv.ADMIN_CMD, true);
            if (!IsPostBack)
            {
                dropProcedure.DataSource = objProc.GetStoredProcedures();
                dropProcedure.DataTextField = "completeName";
                dropProcedure.DataValueField = "id";
                dropProcedure.DataBind();

                ListItem myItem = dropProcedure.Items.FindByValue(Request.QueryString["id"].ToString());
                if (myItem != null)
                    myItem.Selected = true;

                objProc.ID = Convert.ToInt64(dropProcedure.SelectedValue);
                objProc.LoadProperties();

                //load properties
                loadProperties(objProc);

                lblCommandName.Text = AppEnv.CommandName();
            }
        }

        private void loadProperties(_StoredProcedure objProc)
        {
            //Load links
            lnkProcsList.NavigateUrl = AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.Store));
            lnkProcExec.NavigateUrl = AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.StoreAction)) + "&action=exec&id=" + objProc.ID;
            lnkProcDrop.NavigateUrl = AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.StoreAction)) + "&action=drop&id=" + objProc.ID;
            lnkProcRename.NavigateUrl = AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.StoreAction)) + "&action=rename&id=" + objProc.ID;
            try
            {
                //definition
                loadDefinition(objProc);
                //privileges
                loadPrivileges(objProc);
                //dependencies
                //...
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = "<p>" + ex.Message + "</p>";
            }
        }

        private void loadDefinition(_StoredProcedure objProc)
        {
            txtDefinition.Text = "";
            objProc.SetDefinition();
            while (objProc.Definition.Read())
            {
                txtDefinition.Text += objProc.Definition.GetString(0).ToString();
            }
        }

        private void loadPrivileges(_StoredProcedure objProc)
        {
            //set privileges
            try
            {
                privilegesDataTable = objProc.GetPrivilegies();
            }
            catch (Exception)
            {
                privilegesDataTable = null;
            }

            gridUsers.DataSource = objProc.Users();
            gridUsers.DataBind();
            gridRoles.DataSource = objProc.Roles();
            gridRoles.DataBind();
        }

        protected void gridUsers_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (privilegesDataTable != null)
            {
                foreach (DataRow objRow in privilegesDataTable.Rows)
                {
                    if (objRow["Grantee"].ToString() == e.Row.Cells[0].Text)
                    {
                        CheckBox myCheck = (CheckBox)e.Row.FindControl("chkExecute");
                        myCheck.Checked = true;
                    }
                }
            }
        }

        protected void gridRoles_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (privilegesDataTable != null)
            {
                foreach (DataRow objRow in privilegesDataTable.Rows)
                {
                    if (objRow["Grantee"].ToString() == e.Row.Cells[0].Text)
                    {
                        CheckBox myCheck = (CheckBox)e.Row.FindControl("chkExecute");
                        myCheck.Checked = true;
                    }
                }
            }
        }

        protected void btnUpdateDef_Click(object sender, EventArgs e)
        {
            objProc.ID = Convert.ToInt64(dropProcedure.SelectedValue);
            objProc.LoadProperties();
            try
            {
                //if backup needed create a copy
                if (checkBackup.Checked)
                {
                    //rename current Procedure
                    objProc.Rename();
                }
                else
                {
                    //drop Procedure
                    objProc.Drop();
                }

                //execute definition
                objProc.ExecuteQuery(txtDefinition.Text);
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = "<p>" + ex.Message + "</p>";
            }
        }

        protected void btnGrant_Click(object sender, EventArgs e)
        {
            objProc.ID = Convert.ToInt64(dropProcedure.SelectedValue);
            objProc.LoadProperties();
            try
            {
                foreach (GridViewRow userRow in gridUsers.Rows)
                {

                    CheckBox myCheck = (CheckBox)userRow.FindControl("chkExecute");
                    if (myCheck != null)
                    {
                        if (myCheck.Checked)
                        {
                            objProc.GrantExecute(userRow.Cells[0].Text);
                        }
                        else
                        {
                            objProc.RevokeExecute(userRow.Cells[0].Text);
                        }
                    }
                }

                foreach (GridViewRow roleRow in gridRoles.Rows)
                {
                    CheckBox myCheck = (CheckBox)roleRow.FindControl("chkExecute");
                    if (myCheck != null)
                    {
                        if (myCheck.Checked)
                        {
                            objProc.GrantExecute(roleRow.Cells[0].Text);
                        }
                        else
                        {
                            objProc.RevokeExecute(roleRow.Cells[0].Text);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = "<p>" + ex.Message + "</p>";
            }
        }
    }
}